// pages/childmessage/childmessage.js
const app = getApp()
const GetPeriod = require("../../utils/getperiod.js");
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    kid: null,
    kidStr: null,
    date: null,
    photoUrl: null,
    kidName: null,
    isHalalFood: 0,
    kidId: null,
    array: ["汉族", "回族", "苗族", "彝族", "朝鲜族", "蒙古族", "壮族", "满族", "维吾尔族", "土家族", "藏族", "布依族", "侗族", "瑶族", "白族",
      "哈尼族", "哈萨克族", "黎族", "布朗族", "傣族", "畲族", "傈僳族", "仡佬族", "东乡族", "高山族", "拉祜族", "水族", "佤族", "纳西族", "羌族", "土族",
      "仫佬族", "锡伯族", "柯尔克孜族", "达斡尔族", "景颇族", "毛南族", "撒拉族", "塔吉克族", "阿昌族", "普米族", "鄂温克族", "怒族", "京族", "基诺族",
      "德昂族", "保安族", "俄罗斯族", "裕固族", "乌兹别克族", "门巴族", "鄂伦春族", "独龙族", "塔塔尔族", "赫哲族", "珞巴族"
    ],
    array1: ["女", "男"],
    index: 0,
    index1: 0,
    qiniuToken: "",
    national: 1,
    nationalName:"",
    kidUrl: null,
    sex: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  
  onLoad: function (options) {
    var kidStr = options.kidStr
    var kids = JSON.parse(kidStr)
    console.log(options.kidStr)
    var index = -1;
    for (var i = 0; i < this.data.array.length; i++) {
      if (this.data.array[i] == kids.National) {
        index = i
      }
    }

    this.setData({
      kid: kids,
      photoUrl: kids.PhotoUrl,
      kidUrl: kids.PhotoUrl,
      kidName: kids.Name,
      isHalalFood: kids.IsHalalFood,
      index: index,
      index1: kids.Sex,
      national: parseInt(index) + 1,
      date: kids.Brithday,
      kidId: kids.UserID,
      sex: kids.Sex,
      nationalName:kids.National
    })
  },

  // date: GetPeriod.formatDate(this.stringToDate(kids.Brithday)),
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getQiniuToken();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  switchChange: function (e) {
    console.log(e.detail.value)
    var flag = 0;
    if (e.detail.value) {
      flag = 1
    }
    this.setData({
      isHalalFood: flag
    })
  },
  changeDate(e) {
    this.setData({
      date: e.detail.value
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var nationalName=this.data.array[e.detail.value]
    this.setData({
      index: e.detail.value,
      national: parseInt(e.detail.value) + 1,
      nationalName:nationalName
    });
  },

  bindPickerChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index1: e.detail.value,
      sex: e.detail.value,
    });
  },


  kidNameInput: function (e) {
    this.setData({
      kidName: e.detail.value
    })
  },
  btnclick: function (e) {
    if (this.data.kidName == null || this.data.kidName.length == 0) {
      wx.showToast({
        title: "请输入姓名",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return;
    }


    if (this.data.kidUrl != this.data.photoUrl) {
      this.sendImge()
    } else {
      this.saveData();
    }
  },

  changeImg: function (e) {

    var that = this;
    wx.chooseImage({
      count: 1, // 默认最多上传9张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 
        // that.setData({
        //   photoUrl: tempFilePaths[0]
        // })
        wx.navigateTo({
          url: '../image/image?imagePath='+tempFilePaths[0]+"&type=0"
        })
      }

    })
    console.log(this.data.photoUrl)
  },



  saveData: function (e) {



    var that = this;

    var message = {
      "kidname": that.data.kidName,
      "nation": that.data.national,
      "brithday": that.data.date,
      "sex": that.data.sex,
      "isHalalFood": that.data.isHalalFood,
      "headicon": that.data.photoUrl
    }

    var data = {
      "userid": app.globalData.userId,
      "kidid": that.data.kidId,
      "schoolid": app.globalData.schoolId,
      "update": message,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "modify_kid_info"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res)
        if (res.data.status == 0) {
          wx.showToast({
            title: "修改成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          //直接调用上一个页面的setData()方法，把数据存到上一个页面中去

          var kid = that.data.kid
          kid.National=that.data.nationalName
          kid.Sex=that.data.sex
          kid.Name=that.data.kidName
          kid.Brithday=that.data.date
          kid.IsHalalFood=that.data.isHalalFood
          kid.PhotoUrl=that.data.photoUrl
          prevPage.setData({
            kid: kid,
            kidStr:JSON.stringify(kid)
          })

          wx.navigateBack({ //返回
            delta: 1
          })
        } else {
          wx.showToast({
            title: "修改信息失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }

      },
      fail: function (res) {
        wx.showToast({
          title: "修改信息失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  getQiniuToken: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan
    }
    wx.request({
      url: app.globalData.serverQiNiuUrl,
      data: {
        "data": JSON.stringify(data)
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          that.setData({
            qiniuToken: res.data.data.token
          })
        } else {

        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  sendImge: function () {

    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var _this = this
    var filepath = this.data.photoUrl
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
    qiniuUploader.upload(filepath, res => {
      console.log(res)
      var url = res.imageURL
      _this.setData({
        //注意这中间有个"/"在这上面耽误了半个小时
        photoUrl: url
      })
      _this.saveData()
    }, (error) => {
      wx.showToast({
        title: "修改失败",
        icon: 'none',
        duration: 1000,
        mask: true
      })
    }, {
      key: "jygy/" + "photo/" + app.globalData.schoolId + "/" + app.globalData.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".jpg",
      region: 'NCN',
      uptoken: _this.data.qiniuToken,
      uploadURL: 'https://up-z1.qbox.me',
      domain: 'http://img.beiguanhuai.com',
    })

  },


  //为了方法简单，使用该方法前统一把字符转换为'yyyy-MM-dd hh:mm:ss' 格式

  stringToDate: function (dateStr) {

    //若月份、日期、小时、分钟、秒未满10的情况，取整时祛除下前面的0(如04转为4)，否则取整会失败。

    let fullYear = parseInt(dateStr.substring(0, 4));

    let month = parseInt(dateStr.substring(5, 7).substring(0, 1) == '0' ? dateStr.substring(6, 7) : dateStr.substring(5, 7));

    let day = parseInt(dateStr.substring(8, 10).substring(0, 1) == '0' ? dateStr.substring(9, 10) : dateStr.substring(8, 10));

    let hour = parseInt(dateStr.substring(11, 13).substring(0, 1) == '0' ? dateStr.substring(12, 13) : dateStr.substring(11, 13));

    let minute = parseInt(dateStr.substring(14, 16).substring(0, 1) == '0' ? dateStr.substring(15, 16) : dateStr.substring(14, 16));

    let second = parseInt(dateStr.substring(17, 19).substring(0, 1) == '0' ? dateStr.substring(18, 19) : dateStr.substring(17, 19));

    return new Date(fullYear, month - 1, day, hour, minute, second);

  },
})